const Question = require('../models/questionSchema');

class QuestionCtl{
    //问题查询
    async find(ctx){
        //limit 第几个开始  skip跳过多少个取多少个  Math.max选最大的一项 RegExp正则匹配
        const { per_page = 10 } = ctx.query;
        const page = Math.max(ctx.query.page * 1,1)-1;
        const perPage = Math.max(per_page * 1,1);
        const q = new RegExp(ctx.query.q) 
        ctx.body = await Question.find({ $or: [{title: q},{description: q}]}).limit(perPage).skip(page * perPage);
    }
    //查询某个问题可存在
    async checkTopicExist(ctx, next){
        console.log(ctx.state.user)
        const questions = await Question.findById(ctx.params.id).select('+questioner');
        ctx.state.question = questions;
        if(!questions){ ctx.throw(404,'问题不存在')}
        await next();
    }
     //判断该话题是否是该用户的中间件
     async checkQuestioner(ctx, next){
        const { question } = ctx.state;
        console.log(question)
        console.log(ctx.state.user)
        if(question.questioner.toString() !== ctx.state.user._id){ ctx.throw('403','没有权限')}
        await next();
    }
    //查询某个问题
    async findById(ctx){
        const { fields = '' } = ctx.query;
        const seletFields = fields.split(';').filter(f => f).map(f => '+' + f).join("");
        const questions = await Question.findById(ctx.params.id).select(seletFields).populate('questioner topics');
        ctx.body = questions;
    }
    //创建问题
    async create(ctx){
        ctx.verifyParams({
            title: { type: 'string', required: true },
            description: { type: 'string', required: false},
        })
        const questions = await new Question({...ctx.request.body, questioner: ctx.state.user._id}).save();
        ctx.body = questions;
    }
    //修改问题
    async update(ctx){
        console.log(ctx.state.user)
        ctx.verifyParams({
            title: { type: 'string', required: true },
            description: { type: 'string', required: false},
        })
        await ctx.state.question.update(ctx.request.body);
        //这个topic是更新前的信息 要跟新后的信息需要自己去撸 这里不重要
        ctx.body = ctx.state.question;
    }
    //删除某个问题
    async delete(ctx){
        await Question.findByIdAndRemove(ctx.params.id ); 
        ctx.status = 204;
    }
}

module.exports=new QuestionCtl();